package com.example.tnuser.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.tnuser.mapper.ReportMapper;
import com.example.tnuser.service.ReportService;
import com.example.tnuser.service.UserService;
import com.example.tnuser.service.impl.UserServiceImpl;
import com.yc.pojo.User;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.yc.pojo.House;
import com.yc.pojo.Report;
import com.yc.pojo.ReportDTO;
import com.yc.vo.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import com.yc.vo.Uservo;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("user")
public class UserController {
    @Autowired
    private RedisTemplate redisTemplate;

    @Resource
    private ReportMapper reportMapper;

    @Resource
    private UserService userService;

    @Resource
    private ReportService reportService;

    @Resource
    private UserServiceImpl userServiceImpl;

    @RequestMapping("info")
    public Result getInfo(Integer userId){
        return Result.success("success",userService.getById(userId));
    }
    //举报
    @PostMapping("report")
    public Result report(@RequestBody Report report){
        LambdaQueryWrapper<Report> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(Report::getUserId,report.getUserId())
                    .eq(Report::getReporterId,report.getReporterId())
                    .eq(Report::getHouseId,report.getHouseId());
        Report report1 = reportService.getOne(queryWrapper);
        if (report1==null){
            reportService.save(report);
            return Result.success("举报成功");
        }else {
            return Result.failure("请勿重复举报");
        }
    }

    //获取举报信息
    @GetMapping("report/get")
    public Result get(){
        List<ReportDTO> list= reportMapper.selectJoinList(ReportDTO.class, new MPJLambdaWrapper<Report>()
                .selectAll(Report.class)
                .select(User::getUserName)
                .selectAs(House::getIntroduce,ReportDTO::getHouseName)
                .leftJoin(User.class, User::getId,ReportDTO::getUserId)
                .leftJoin(House.class,House::getId,ReportDTO::getHouseId)
        ).stream().map(item->{
            LambdaQueryWrapper<User> queryWrapper=new LambdaQueryWrapper<>();
            queryWrapper.select(User::getUserName).eq(User::getId,item.getReporterId());
            item.setReportedName(userService.getOne(queryWrapper).getUserName());
            item.setHouseName(item.getHouseName().split(" ")[0]);
            return item;
        }).collect(Collectors.toList());
        return Result.success("success",list);
    }

    //处理举报是否通过并扣取信誉分
    @GetMapping("report/judge")
    @Transactional
    public Result judge(int id,int state){
        LambdaUpdateWrapper<Report> updateWrapper=new LambdaUpdateWrapper<>();
        updateWrapper.set(Report::getState,state).eq(Report::getId,id);
        boolean update = reportService.update(updateWrapper);
        if (update){
            Report report = reportService.getById(id);
            User user = userService.getById(report.getUserId());
            if (user.getReputation()==0){
                return Result.failure("该用户信誉分已达最低");
            }else
                user.setReputation(user.getReputation()-5);
            userService.saveOrUpdate(user);
            return Result.success("success");
        }
        else
            return Result.failure("failure");
    }

    //返回user信息
    @RequestMapping("master")
    public User getMaster(Integer masterId){
        return userService.getById(masterId);
    }

    //后台返回全部用户信息
    @RequestMapping("list")
    public Result list(String userName,int currentPage,int pageSize){
        Page<User> page=new Page<>(currentPage,pageSize);
        LambdaQueryWrapper<User> queryWrapper=new LambdaQueryWrapper<>();
        if (userName!=null&&userName!=""){
            queryWrapper.like(User::getUserName,userName).or().like(User::getPhone,userName);
        }
        userService.page(page,queryWrapper);
        return Result.success("success",page);
    }

    //删除
    @RequestMapping("delete")
    public Result delete(int id){
        userService.removeById(id);
        return Result.success("success");
    }

    //保存
    @PostMapping("save")
    public Result save(@RequestBody @Valid User user, Errors errors){
        if (errors.hasErrors()){
            return Result.failure("用户添加数据错误",errors.getAllErrors());
        }
        //设置默认头像
        user.setImage("https://thirdwx.qlogo.cn/mmopen/vi_32/UDZGqoED7TqV5fFUiblibZf3njWoLLRnb58JdWp6yOia8LTs5dAaAZF7lXOLRg3cmvBGZMegP7VSTK3V6cyjJsokA/132");
        userService.saveOrUpdate(user);
        return Result.success("success");
    }

    @PostMapping("wx/save")
    public Result wxSave(@RequestBody User user){
        userService.saveOrUpdate(user);
        return Result.success("success");
    }
	/**
     * 点击登陆时根据openid进行用户的查询
     *
     * @param openid
     * @return
     */
    @RequestMapping("wx/getuser")
    public User getUser(String openid) {
        User user = userServiceImpl.selectUser(openid);
        if (user != null) {
            return user;
        }
        return user;
    }


    /**
     * 小程序用户绑定手机号
     * @param uservo
     * @return
     */
    @PostMapping("wx/register")
    public Result register(@RequestBody Uservo uservo) {
        String openid = uservo.getOpenid();
        String phone = uservo.getPhone();
        String img = uservo.getImg();
        if (openid == null || "".equals(openid)) {
            return Result.failure("openid 为空");
        }
        if (phone == null || "".equals(phone)){
            return Result.failure("用户名为空");
        }
        boolean havaPhone = userServiceImpl.havaPhone(phone);
        if (havaPhone == true) {
            boolean havaCode = userServiceImpl.havaCode(phone);
            if (havaCode == true) {
                return Result.failure("该手机号码已经被其他微信号绑定!");
            }
            if (havaCode == false) {
                userServiceImpl.updateUser(phone, openid,img);
                return Result.success("绑定已有账户成功");
            }
        }
        userServiceImpl.insertUser(phone, openid,img);
        return Result.success("绑定成功");
    }}
